import { ElMessage } from "@/components/message"
import { ElNotification } from 'element-plus'

let timerout = null

const useElMessage = (options) => {
    clearTimeout(timerout)
    timerout = setTimeout(() => {
        if (typeof options === "string") {
            options = { message: options }
        }
        const { customClass = "", notice = false, showIcon = true } = options
        options.showClose = options.showClose === undefined ? false : options.showClose
        options.clickClose = options.clickClose === undefined && options.duration === 0 ? true : options.clickClose
        options.customClass = `use-el-message ${customClass} ${showIcon ? "" : "hidden-icon"} forbid-select`
        options.offset = 10

        if (notice) {
            if (options.clickClose) {
                const click = options.onClick
                options.onClick = () => {
                    ElNotification.closeAll()
                    if (click) click()
                }
            }
            options.message = options.message.replace(/\n/g, '<br/>')
            ElNotification.closeAll()
            return ElNotification(options)
        } else {
            if (options.clickClose) {
                const click = options.onClick
                options.onClick = (instance) => {
                    instance.handler.close()
                    if (click) click(instance)
                }
            }
            const message = options.title && options.message ? `<h3 class='el-message__title'>${options.title}</h3><div>${options.message}</div>` : options.title || options.message
            options.dangerouslyUseHTMLString = (options.title && options.message) || message.includes('\n') ? true : options.dangerouslyUseHTMLString
            options.message = message.replace(/\n/g, '<br/>')
            ElMessage.closeAll()
            return ElMessage(options)
        }
    });
}

["success", "warning", "info", "error"].forEach(type => {
    useElMessage[type] = (options) => {
        if (typeof options === "string") {
            options = { message: options }
        }
        options.type = type
        return useElMessage(options)
    }
})

export default useElMessage